package com.app.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.app.common.Result;
import com.app.mapper.AdminUserMapper;
import com.app.mapper.UserMapper;
import com.app.model.AdminRoleModel;
import com.app.model.AdminUserModel;
import com.app.model.UserModel;
import com.app.service.AdminRoleService;
import com.app.service.AdminUserService;
import com.app.service.IPlatformChangeRecordService;
import com.app.service.UserService;
import com.app.service.impl.UserServiceImpl;
import com.app.utils.CacheUtil;
import com.app.utils.CommonHelp;
import com.app.utils.IpUtil;
import com.app.utils.TokenUtils;
import com.app.vo.AdminUserVo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.*;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;

@Slf4j
@RestController
@RequestMapping("/adminUser")
public class AdminUserController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private AdminRoleService adminRoleService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;

    //发送验证码
    @GetMapping("/captcha")
    public Result<Object> captcha(HttpServletResponse response) throws Exception {
        response.setHeader("Cache-Control", "no-store,no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = String.format("%04d", new Random().nextInt(9999));
        log.info(text);
        //生成图片验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(90, 36);
        BufferedImage image = (BufferedImage) lineCaptcha.createImage(text);
//        BufferedImage image = producter.createImage(text);
        UUID uuid = UUID.randomUUID();
        //保存验证码到本地缓存
        CacheUtil.put(uuid.toString(), text);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", stream);
        String base64 = Base64.getEncoder().encodeToString(stream.toByteArray());
        JSONObject data = new JSONObject();
        String base666 = "data:image/png;base64," + base64;
        data.put("key", uuid);
        data.put("code", base666);
        return Result.success(data);
    }

    //todo 管理端用测试时用来获得token的接口
    @GetMapping("/adminToken")
    public Result<Object> adminToken(Integer id) {
        AdminUserModel user = adminUserService.getById(id);
        if (user == null) {
            return Result.error(500, "用户名或密码错误");
        }
        String token = TokenUtils.sign(String.valueOf(user.getId()));
        return Result.success(token);
    }

    public static void main(String[] args) {
        String salt = "suBei_bz";
        String md5Password = md5Hex("YFHJ888888" + salt);
        Console.log(md5Password);
    }
    //后台登录
    @PostMapping("/login")
    public Result<Object> login(@RequestBody JSONObject json, HttpServletRequest request) {
        String password = json.get("password").toString();
        String key = json.get("key").toString();
        String code = json.get("code").toString();
        String username = json.get("username").toString();
        String salt = "suBei_bz";
        String md5Password = md5Hex(password + salt);
        Object code1 = CacheUtil.get(key);
        if (code1 == null) {
            return Result.error(500, "验证码已失效或已过期");
        }
        if (!code1.equals(code)) {
            return Result.error(500, "验证码错误");
        }
        AdminUserModel user = adminUserService.login(username, md5Password);
        if (user == null) {
            return Result.error(500, "用户名或密码错误");
        }
        int status = user.getStatus();
        if (status == 0) {
            return Result.error(500, "该账户已被禁用");
        }
        String token = TokenUtils.sign(String.valueOf(user.getId()));
        String ip = IpUtil.getIpAddress(request);
        user.setToken(token);
        user.setLastLoginIp(ip);
        user.setLastLoginTime(CommonHelp.getNowTimestamp());
        adminUserService.updateById(user);
        user.setPassword(null);
        return Result.success(user);
    }

    @GetMapping("/logOut")//通过token查权限
    public Result<Object> logOut(@RequestParam("token") String token, HttpServletRequest request) {
//        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
//        RoleModel roleModel = roleService.getRoleByRoleId(user.getRoles());
//        List<String> roleModelList = new ArrayList<>();
//        String[] roleArr = roleModel.getRules().split(";");//获取图片集合字符串
//        if(roleArr != null){
//            for (int i = 0; i < roleArr.length; i++) {
//                roleModelList.add(roleArr[i]);
//            }
//            user.setPermissionList(roleModelList);
//        }
        return Result.success(null);
    }

    //通过token查权限
    @GetMapping("/getAdminInfoByToken")
    public Result<Object> getAdminInfoByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.parseInt(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }

        AdminRoleModel roleModel = adminRoleService.getById(adminUser.getRoleId());
        List<String> roleModelList = new ArrayList<>();
        String[] roleArr = roleModel.getRules().split(",");//获取字符串
        if (roleArr != null) {
            for (int i = 0; i < roleArr.length; i++) {
                roleModelList.add(roleArr[i]);
            }
            adminUser.setPermissionList(roleModelList);
        }
        return Result.success(adminUser);
    }

    //查询管理员列表
    @GetMapping("/getAdminList")
    public Result<Object> getAdminList(Integer page, Integer limit, String keyword, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.parseInt(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }

        AdminUserVo adminUserList = adminUserService.getAdminList(page, limit, keyword);
        return Result.success(adminUserList);
    }

    //查询管理员列表
    @GetMapping("/getAdminById")
    public Result<Object> getAdminById(Integer id, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.parseInt(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }
        AdminUserModel adminUserModel = adminUserService.getById(id);
        if (StrUtil.isNotBlank(adminUserModel.getAreaCode())) {
            List<String> list = JSON.parseObject(adminUserModel.getAreaCode(), new TypeReference<List<String>>() {
            });
            adminUserModel.setValue(list);
        }
        adminUserModel.setPassword(null);
        return Result.success(adminUserModel);
    }

    //后台更新密码
    @PostMapping("/updatePassWord")
    public Result<Object> updatePassWord(@RequestParam("id") Integer id,
                                         @RequestParam("password") String password) {
        AdminUserModel user = adminUserService.getById(id);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        String salt = "suBei_bz";
        String newWord = md5Hex(password + salt);
        user.setPassword(newWord);
        adminUserService.updateById(user);
        return Result.success("修改成功");
    }

    //管理员管理
    //添加和编辑管理员
    @PostMapping("/addAndUpdateAdmin")
    public Result<Object> addAndUpdateAdmin(@RequestBody AdminUserModel adminUserModel, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.parseInt(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }
        String phone = adminUserModel.getPhone();
        UserModel userModel = userService.getUserByPhone(phone);
        if (userModel == null) {
            return Result.error(400, "请该手机号所属用户先登录注册小程序");
        }
        Integer areaId = adminUserModel.getAreaId();
        String salt = "suBei_bz";
        if (adminUserModel.getRoleId() != null) {
            AdminRoleModel byId = adminRoleService.getById(adminUserModel.getRoleId());
            adminUserModel.setRoleName(byId.getRoleName());
        }
        if (CollectionUtil.isNotEmpty(adminUserModel.getValue())) {
            adminUserModel.setAreaCode(JSON.toJSONString(adminUserModel.getValue()));
        }
        if (adminUserModel.getId() == null) {
            Wrapper<AdminUserModel> whetherThereIsAProxyUserWhoChangesMobilePhoneNumber = new QueryWrapper<AdminUserModel>()
                    .eq("phone", phone);
            if (adminUserMapper.selectCount(whetherThereIsAProxyUserWhoChangesMobilePhoneNumber) > 0) {
                return Result.error(400, "该用户已是其他地区代理，请重新分配用户");
            }
            Wrapper<AdminUserModel> wq = new QueryWrapper<AdminUserModel>()
                    .eq("area_id", areaId)
                    .eq("role_id", adminUserModel.getRoleId());
            List<AdminUserModel> adminUserModels = adminUserMapper.selectList(wq);
            if (!adminUserModels.isEmpty()) {
                return Result.error(400, "该地区代理已存在，请重新分配");
            }
            String password = adminUserModel.getPassword();
            String newPassWord = md5Hex(password + salt);
            adminUserModel.setPassword(newPassWord);
            adminUserModel.setCreateTime(CommonHelp.getNowTimestamp());
            adminUserService.save(adminUserModel);
            if (adminUserModel.getRoleId() == 3 || adminUserModel.getRoleId() == 4) {
                userModel.setRoleId(adminUserModel.getRoleId());
                userService.updateById(userModel);
            }
        }
        else {
            AdminUserModel user = adminUserService.getById(adminUserModel.getId());
            if (user != null) {
                adminUserModel.setId(user.getId());
            } else {
                return Result.success("用户不存在");
            }
            if (adminUserModel.getPassword() != null) {
                String password = adminUserModel.getPassword();
                String newPassWord = md5Hex(password + salt);
                adminUserModel.setPassword(newPassWord);
            }
            adminUserModel.setUpdateTime(CommonHelp.getNowTimestamp());
            adminUserService.updateById(adminUserModel);
        }
//        userModel.setAreaCode(adminUserModel.getAreaCode());
//        userModel.setAreaId(adminUserModel.getAreaId().toString());
        userServiceImpl.updateUserInfo(userModel);
        return Result.success("操作成功");
    }

    //修改状态
    @GetMapping("/updateAdminStatus")
    public Result<Object> updateAdminStatus(@RequestParam("id") Integer id,
                                            @RequestParam("status") Integer status, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.parseInt(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }
        AdminUserModel adminUserModel = new AdminUserModel();
        adminUserModel.setId(id);
        adminUserModel.setStatus(status);
        adminUserService.updateById(adminUserModel);

        AdminUserModel adminUserServiceById = adminUserService.getById(id);
        String phone = adminUserServiceById.getPhone();
        if (phone != "1") {
            UserModel userModel = userService.getUserByPhone(phone);
            if (status == 1) {
                userModel.setVip(1);
                if(StrUtil.isBlankIfStr(userModel.getInvitationCode()))
                {
                    this.userService.generateInvitationCode(userModel);
                }
                userMapper.updateById(userModel);
            } else if (status == 0) {
                //取消会员身份
                userModel.setVip(2);
                userMapper.updateById(userModel);
            }
        }
        return Result.success("操作成功");
    }

    //根据ID删除管理员信息
    @GetMapping("/delAdmin")
    public Result<Object> delAdmin(Integer id, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel adminUser = adminUserService.getById(Integer.parseInt(adminId));
        if (adminUser == null) {
            return Result.error(405, "用户不存在");
        }
        adminUserService.removeById(id);
        return Result.success("删除成功");
    }

    @Autowired
    private IPlatformChangeRecordService platformChangeRecordService;


    /**
     * 平台用户价值
     *
     * @param request 请求
     * @param type    类型 1券 2积分
     * @return {@link Result}<{@link Object}>
     */
    @GetMapping("/platformUserValue")
    public Result<Object> platformUserValue(@RequestParam(value = "type",defaultValue = "1") Integer type,
                                            @RequestParam(value = "startTime",required = false) String startTime,
                                            @RequestParam(value = "endTime",required = false) String endTime,
                                            HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        return Result.success(this.platformChangeRecordService.statisticalValue(type,startTime,endTime));
    }

    @GetMapping("/platformUserList")
    public Result<Object> platformUserList(@RequestParam(value = "type",defaultValue = "1") Integer type,
                                           @RequestParam(value = "typeName",required = false) String typeName,
                                            @RequestParam(value = "startTime",required = false) String startTime,
                                            @RequestParam(value = "endTime",required = false) String endTime,
                                            @RequestParam(value = "page",defaultValue = "1") Integer page,
                                            @RequestParam(value = "limit",defaultValue = "10") Integer limit,
                                            HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        return Result.success(this.platformChangeRecordService.platformUserList(page,limit,type,typeName,startTime,endTime));
    }


}
